package com.weishui.talking.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import com.weishui.talking.app.TalkingWindow;
import com.weishui.talking.util.Constant;

public class Serversocket implements Runnable{
	static Logger logger = Logger.getLogger(ClientSocket.class);
	private ServerSocket serverSocket;
	private Socket socket;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			serverSocket = new ServerSocket(Constant.serverPort);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		while(true){
			try {
				socket = serverSocket.accept();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("accept socket IOException:",e);
			}catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("accept socket Exception:",e);
			}
			new SocketThread(socket).start();
		}
	}
}
class SocketThread extends Thread{
	static Logger logger = Logger.getLogger(ClientSocket.class);
	private Socket socket;
	BufferedReader br = null;
	SocketThread(Socket socket){
		this.socket = socket;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			String str = null;
			StringBuffer sBuffer = new StringBuffer();
			while((str = br.readLine()) != null){
				sBuffer.append(str);
			}
			TalkingWindow.addLog(sBuffer.toString());
		}catch (IOException e) {
			// TODO Auto-generated catch block
			logger.error("IOException",e);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			logger.error("Exception",e);
		}finally{
			try {
				if(br != null){
					br.close();
				}
				if(socket != null){
					socket.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error("close resource IOException",e);
			}catch (Exception e) {
				// TODO Auto-generated catch block
				logger.error("close resource Exception",e);
			}
		}
	}
	
}
